% 1. load data
clc;
close all;
% [val, text] = xlsread('data_lsLNH.xlsx',1); % load weekly data
load lsLNH

%%
global Standardize showGraph;
global gamma intercept;
Standardize = true;
% showGraph = false;
ls1W = val(:,1); rls1W = ls1W(2:end) - ls1W(1:end-1);
ls1M = val(:,2); rls1M = ls1M(2:end) - ls1M(1:end-1);
ls3M = val(:,3); rls3M = ls3M(2:end) - ls3M(1:end-1);
gap1M1W = ls1M - ls1W;
gap3M1M = ls3M - ls1M;
% ddate = datenum(text(2:end,1),'mm/dd/yyyy');

h = 8;

EMA4_1M =funcEMA(ls1M,4);

Nfull  = size(ls1M,1);
w = [0.34, 0.33, 0.33];             % for compare


Yh_full = ls1M(1+h:end) > ls1M(1:end - h); %up if ls 1M increase

EMAnew = [ls1M(1:3); EMA4_1M(4:end)];
rEMA = EMAnew(2:end) - EMAnew(1:end-1);
% Yh_full = ls1M(1+h:end) > EMAnew(1:end - h); %up if ls 1M increase

Yh = Yh_full(2:end);
% X = [rls1W(1:end-h) rls1M(1:end-h) rls3M(1:end-h) gap3M1M(2:end-h) EMA4_1M(2:end-h)];
X = [rls1M(1:end-h) rls3M(1:end-h) gap3M1M(2:end-h) rEMA(1:end-h)];
N = size(Yh,1);

%divide data into training and test set
ratio = 3/4;
Ntrain = floor(N * ratio);
Ntest = N - Ntrain;

Xtrain = X(1:Ntrain,:); Ytrain = Yh(1:Ntrain);
Xtest = X(Ntrain+1:end,:); Ytest = Yh(Ntrain+1:end);


% 2. scaling data: change data from [a b] -> [0 1] or [-1 1];
% method : using (x - xmin)/(xmax-xmin) in each column;
Xtrain_scale = scalingStandarize(Xtrain);
Xtest_scale = scalingStandarize(Xtest);

%%
% 3. find the optimize C and gamma by grid method
close all;
showGraph = true;
gamma = 1;
intercept = -1;
log2CGrid = [-5 15 2]; log2gammaGrid = [-15 3 2]; %default rbf
% log2CGrid = [10 14 0.5]; log2gammaGrid = [-3 1 0.5];
gridParams = [log2CGrid;log2gammaGrid];
[COpt, gammaOpt] = gridParameterCanonical(Xtrain, Ytrain,gridParams,'rbf');

% [COpt, gammaOpt] = gridParameter(Xtrain, Ytrain_scale);

%%
% 4. Out-of-sample performance:
gamma = gammaOpt;
% params = [COpt, gammaOpt]; 
params = [2044, gammaOpt]; 

% params = params(1,:); %choose only one params
% finalRes = outSamplePerformance(X,Yh,params, Ntrain,'mysigmoid');
finalRes = outSamplePerformance(X,Yh,params, Ntrain,'rbf');
